const request = require('request');
// const fs = require('fs');
// const iconv = require('iconv-lite');
// const cheerio = require('cheerio');
const { Curl } = require('node-libcurl');
// const { URL } = require('url');
const url = require('url');
const controllersWatermark = that = {
	/**
	 * 初始化
	 * @param {Object} req
	 * @param {Object} res
	 */
	async init(req, res) {
		const query = req.query;
		const { url } = query;
		const getUrl = that.getStrUrl(url);
		if (!getUrl) res.send({
			code: -1,
			msg: '未检测到解析地址',
			data: null
		});
		if (that.checkUrl(getUrl, 'douyin')) {
			that.douyin(getUrl, res);
		} else {
			res.send({
				code: -1,
				msg: '未检测到解析地址',
				data: null
			});
		}
	},
	/**
	 * 抖音去水印
	 * @param {Object} url 解析地址
	 * @param {Object} res 响应对象
	 * /video\/(.*)\?/ -视频解析  /note\/(.*)\?/- 图集解析
	 */
	async douyin(url, res) {
		const myURL = url.parse(url);
		console.log(myURL);
		res.send(myURL);
		return;
		const _id = await that.getID(url, /video\/(.*)\?/, /note\/(.*)\?/);
		const _url = `https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=${_id}`;
		res.send(url);
		return;
		const _data = await that.getReqBody(_url);
		if (!_data.item_list.length) {
			res.send({
				code: -1,
				msg: _data.filter_list[0]['detail_msg'],
				data: null
			});
			return;
		}
		let title = _data.item_list[0].share_info.share_title,//标题
			cover = _data.item_list[0]['video']['origin_cover']['url_list'][0],//封面
			images = null,//图集
			video = null;//视频
		if (_data.item_list[0]['images'] && _data.item_list[0]['images'].length) {//图集
			const imgs_url = _data.item_list[0]['images'][0]['url_list'];
			images = imgs_url;
		} else {//视频
			const video_url_init = _data.item_list[0]['video']["play_addr"]["url_list"][0].replace('playwm', 'play');
			const video_url = await that.curl(video_url_init);
			video = video_url;
			// console.log('video_url', video_url);
		}
		const result = {
			title: title,
			images: images,
			cover: cover,
			video: video
		};
		// console.log('解析结果：', result);
		res.send({
			code: 0,
			msg: '解析成功',
			data: result
		})
	},
	curl(url, headers = []) {
		const $headers = headers.length ? headers : ['User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', "Content-Type: application/x-www-form-urlencoded; charset=UTF-8"]
		return new Promise((resolve) => {
			const curl = new Curl();
			curl.setOpt('URL', url);
			curl.setOpt('FOLLOWLOCATION', true);
			curl.setOpt('TIMEOUT', 1000);
			curl.setOpt('SSL_VERIFYPEER', 0);
			curl.setOpt('USE_SSL', 'None');
			curl.setOpt('COOKIEFILE', "");
			curl.setOpt('HTTPHEADER', $headers);
			curl.on('end', function (statusCode, body, headers) {
				if (statusCode == 200) {
					const filterLocation = headers.filter(item => item.location);
					const result = filterLocation.length ? filterLocation[0]['location'] : null;
					resolve(result);
				} else {
					resolve(null);
				}
				// console.info(this.getInfo('TOTAL_TIME'));
				// console.log('headersheaders', headers)
				this.close();
			});
			curl.on('error', function (error) {
				resolve(null);
			});
			curl.perform();
		});
	},
	/**
	 * 获取请求的内容
	 * @param {Object} url 请求地址
	 */
	getReqBody(url) {
		return new Promise((resolve) => {
			request(encodeURI(url), (error, res, body) => {
				if (!error && res.statusCode == 200) {
					const _data = typeof JSON.parse(res.body) != 'undefined' ? JSON.parse(res.body) : {};
					// console.log(body)
					resolve(_data);
				} else resolve(null);
			})
		})
	},
	/**
	 * 根据链接地址和正则规则获取相应id
	 * @param {Object} url 链接地址
	 * @param {Object} reg1 正则表达式1
	 * @param {Object} reg2 正则表达式2
	 */
	getID(url, reg1, reg2 = null) {
		return new Promise((resolve) => {
			request(encodeURI(url), (error, res) => {
				try {
					if (!error && res.statusCode == 200) {
						const check1 = res.request.href.match(reg1) ? res.request.href.match(reg1)[1] : null;
						const check2 = res.request.href.match(reg2) ? res.request.href.match(reg2)[1] : null;
						const result = check1 || check2;
						resolve(result);
					} else resolve(null);
				} catch (e) {
					console.warn('getID有错误抛出：', e);
					resolve(null);
				}
			})
		})
	},
	/**
	 * 获取字符串中的url地址
	 * @param {String} s 字符串
	 */
	getStrUrl(s) {
		var reg = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g;
		var reg = /(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
		s = s.match(reg);
		return (s && s.length ? s[0] : null);
	},
	/**
	 * 检查链接中是否有该值
	 * @param {Object} url 链接地址
	 * @param {Object} val 检查的值
	 */
	checkUrl(url, val) {
		return url.indexOf(val) > -1;
	}
};
module.exports = controllersWatermark;
